import { createRouter, createWebHistory } from 'vue-router';
import { useRouterStore } from '@/store/router';
import routerMaps from '@/router/routerMaps';
import componentMaps from './componentMaps';
import { nextTick } from 'vue';

const modules = import.meta.glob('../views/**/**.vue');

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login.vue'),
      meta: {
        title: '登陆',
      },
    },
    {
      path: '/main',
      name: 'main',
      redirect: '/home',
      component: () => import('@/layout'),
      children: [
        {
          path: '/home',
          name: 'home',
          component: () => import('@/views/home'),
          meta: {
            title: '首页',
          },
        },
        // ...routerMaps,
        // {
        //   // 404
        //   path: '/:pathMatch(.*)*',
        //   name: '404',
        //   component: () => import('@/views/404'),
        //   meta: {
        //     title: '404',
        //   },
        // },
      ],
    },
  ],
});

// 路由拦截
router.beforeEach(async (to, from, next) => {
  if (to.path === '/login') {
    next();
  } else {
    const token = sessionStorage.getItem('token');
    if (token) {
      // ConfigRouter();
      const { isFirstRouter, routerList } = useRouterStore();
      // 存在进入
      // 默认添加路由
      if (!isFirstRouter) {
        setRouter(routerList);
        await nextTick();
        next({
          ...to,
          replace: true,
        });
      } else {
        next();
      }
    } else {
      next({
        path: '/login',
      });
    }
  }
});
const setRouter = async list => {
  const { changeFirstRouter } = useRouterStore();
  list.forEach(item => {
    // 如果是外链或者菜单类型为1，则不添加路由
    if (item.type !== 1 && !item.menuType) {
      router.addRoute('main', { ...item, component: modules[`../views${item.component}.vue`] });
    }
  });
  router.addRoute('main', {
    // 404
    path: '/:pathMatch(.*)*',
    name: '404',
    component: () => import('@/views/404'),
    meta: {
      title: '404',
    },
  });
  changeFirstRouter(true);
};

router.afterEach((to, from) => {
  // 添加路由
  document.title = to.meta.title;
});

export default router;
